﻿using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Threading.Tasks;
using Test_DI.Domain;
using Test_DI.Interface;

namespace Test_DI.Implement
{
    public class EfRespository<T> : IRespository<T> where T : BaseEntity
    {
        private readonly Admin3200DbContext db;

        private DbSet<T> _entity; //内部使用的entity


        protected DbSet<T> Entity  //可查询的
        {
            get
            {
                if(_entity == null)
                {
                    _entity = db.Set<T>();
                }
                return _entity;
            }
        }

        public IQueryable<T> Table
        {
            get
            {

                return Entity;
            }
        }

       

        public EfRespository(Admin3200DbContext dbContext)
        {
            db = dbContext;
        }

        public void Delete(T entity)
        {
            this._entity.Remove(entity); //把Table换成entity

            db.SaveChanges(); //保存更改
        }
        public void Delete(int Id)
        {
            var row = Table.Where(x => x.Id == Id).FirstOrDefault();
            Delete(row);
        }

        public IEnumerable<T> GetAllEntity()
        {
            throw new NotImplementedException();
        }

        public T GetById(int id)
        {
            return _entity.Where(x => x.Id == id).FirstOrDefault();
        }

        public void Insert(T entity)
        {
            _entity.Add(entity);
            db.SaveChanges();
        }

        public void InsertBulk(IEnumerable<T> list)
        {
            _entity.AddRange(list);
            db.SaveChanges();
        }

        public void Update(T entity)
        {
            _entity.Update(entity);
            db.SaveChanges();
        }

        

        int IRespository<T>.Insert(T entity)
        {
            throw new NotImplementedException();
        }
    }
}
